const express = require('express');
const cors = require('cors');
const app = express();
const PORT = 8000;

// 中间件
app.use(cors());
app.use(express.json());

// 模拟医生数据
const mockDoctors = [
    {
        id: 1,
        name: '张医生',
        department: '心内科',
        city: '三门峡市',
        hospital: '三门峡市中心医院',
        title: '主任医师',
        rating: 4.8,
        avatar: 'https://img.icons8.com/color/96/000000/doctor-male.png',
        specialty: '擅长冠心病、高血压、心律失常等心血管疾病的诊治',
        consultationTypes: ['图文咨询', '电话咨询', '视频咨询'],
        price: '¥ 50 起',
        banners: 12,
        views: 45678
    },
    {
        id: 2,
        name: '李医生',
        department: '心内科',
        city: '三门峡市',
        hospital: '三门峡市人民医院',
        title: '副主任医师',
        rating: 4.6,
        avatar: 'https://img.icons8.com/color/96/000000/doctor-female.png',
        specialty: '擅长心力衰竭、心肌病等疾病的诊治',
        consultationTypes: ['图文咨询', '电话咨询'],
        price: '¥ 35 起',
        banners: 8,
        views: 23456
    },
    {
        id: 3,
        name: '王医生',
        department: '神经内科',
        city: '三门峡市',
        hospital: '三门峡市中心医院',
        title: '主治医师',
        rating: 4.5,
        avatar: 'https://img.icons8.com/color/96/000000/doctor-male.png',
        specialty: '擅长脑血管病、癫痫、帕金森病等神经系统疾病的诊治',
        consultationTypes: ['图文咨询', '电话咨询'],
        price: '¥ 30 起',
        banners: 6,
        views: 18923
    },
    {
        id: 4,
        name: '刘医生',
        department: '儿科',
        city: '三门峡市',
        hospital: '三门峡市儿童医院',
        title: '主任医师',
        rating: 4.9,
        avatar: 'https://img.icons8.com/color/96/000000/doctor-female.png',
        specialty: '擅长儿童常见病、多发病的诊治，儿童生长发育评估',
        consultationTypes: ['图文咨询', '电话咨询', '视频咨询'],
        price: '¥ 40 起',
        banners: 15,
        views: 56789
    },
    {
        id: 5,
        name: '陈医生',
        department: '骨科',
        city: '三门峡市',
        hospital: '三门峡市骨科医院',
        title: '副主任医师',
        rating: 4.7,
        avatar: 'https://img.icons8.com/color/96/000000/doctor-male.png',
        specialty: '擅长骨折、关节疾病、脊柱疾病的诊治和手术治疗',
        consultationTypes: ['图文咨询', '电话咨询'],
        price: '¥ 45 起',
        banners: 10,
        views: 34567
    }
];

// 医生列表接口
app.get('/doctor/list', (req, res) => {
    try {
        const { pageCode = '1', pageSize = '10', city, admin, name, order = 'desc' } = req.query;
        
        let filteredDoctors = [...mockDoctors];
        
        // 按城市筛选
        if (city) {
            filteredDoctors = filteredDoctors.filter(doctor => 
                doctor.city.includes(city)
            );
        }
        
        // 按科室筛选
        if (admin) {
            filteredDoctors = filteredDoctors.filter(doctor => 
                doctor.department.includes(admin)
            );
        }
        
        // 按姓名筛选
        if (name) {
            filteredDoctors = filteredDoctors.filter(doctor => 
                doctor.name.includes(name)
            );
        }
        
        // 排序
        if (order === 'desc') {
            filteredDoctors.sort((a, b) => b.rating - a.rating);
        } else {
            filteredDoctors.sort((a, b) => a.rating - b.rating);
        }
        
        // 分页
        const page = parseInt(pageCode);
        const size = parseInt(pageSize);
        const startIndex = (page - 1) * size;
        const endIndex = startIndex + size;
        const paginatedDoctors = filteredDoctors.slice(startIndex, endIndex);
        
        res.json({
            success: true,
            data: paginatedDoctors,
            total: filteredDoctors.length,
            page: page,
            pageSize: size,
            message: '获取医生列表成功'
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '服务器错误',
            error: error.message
        });
    }
});

// 搜索接口
app.get('/search', (req, res) => {
    try {
        const { pageCode = '1', pageSize = '10', searchValue = '' } = req.query;
        
        let searchResults = [];
        
        // 搜索医生
        const doctorResults = mockDoctors.filter(doctor => 
            doctor.name.includes(searchValue) ||
            doctor.department.includes(searchValue) ||
            doctor.hospital.includes(searchValue) ||
            doctor.specialty.includes(searchValue)
        ).map(doctor => ({
            id: doctor.id,
            name: doctor.name,
            title: doctor.title,
            department: doctor.department,
            hospital: doctor.hospital,
            content: doctor.specialty,
            type: 'doctor'
        }));
        
        searchResults = searchResults.concat(doctorResults);
        
        // 分页
        const page = parseInt(pageCode);
        const size = parseInt(pageSize);
        const startIndex = (page - 1) * size;
        const endIndex = startIndex + size;
        const paginatedResults = searchResults.slice(startIndex, endIndex);
        
        res.json({
            success: true,
            data: paginatedResults,
            total: searchResults.length,
            page: page,
            pageSize: size,
            message: '搜索成功'
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '搜索失败',
            error: error.message
        });
    }
});

// 搜索科室接口
app.get('/search/department', (req, res) => {
    try {
        const { pageCode = '1', pageSize = '10', searchValue = '' } = req.query;
        
        // 从医生数据中提取科室信息
        const departments = [...new Set(mockDoctors.map(doctor => doctor.department))];
        
        let searchResults = departments
            .filter(dept => dept.includes(searchValue))
            .map((dept, index) => ({
                id: index + 1,
                departmentName: dept,
                departmentType: '临床科室',
                departmentDescription: `${dept}是医院的重要科室，提供专业的医疗服务`,
                hospital: '三门峡市中心医院',
                type: 'department'
            }));
        
        // 分页
        const page = parseInt(pageCode);
        const size = parseInt(pageSize);
        const startIndex = (page - 1) * size;
        const endIndex = startIndex + size;
        const paginatedResults = searchResults.slice(startIndex, endIndex);
        
        res.json({
            success: true,
            data: paginatedResults,
            total: searchResults.length,
            page: page,
            pageSize: size,
            message: '科室搜索成功'
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '科室搜索失败',
            error: error.message
        });
    }
});

// 健康检查接口
app.get('/health', (req, res) => {
    res.json({ status: 'OK', message: '服务器运行正常' });
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`医生服务服务器运行在 http://localhost:${PORT}`);
    console.log(`医生列表接口: http://localhost:${PORT}/doctor/list`);
});
